package com.yexiao.cofe.resolver;

import cn.hutool.core.util.StrUtil;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class TokenResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        IRequestToken annotation = parameter.getParameterAnnotation(IRequestToken.class);
        return annotation != null && String.class.isAssignableFrom(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String authorization = webRequest.getHeader("authorization");
        if(StrUtil.isEmpty(authorization)) {
            authorization = webRequest.getHeader("Token");
        }
        if(StrUtil.isEmpty(authorization)) {
            authorization = webRequest.getHeader("token");
        }
        if(StrUtil.isEmpty(authorization)) {
            authorization = webRequest.getHeader("Authorization");
        }

        if(StrUtil.isNotEmpty(authorization) && authorization.startsWith("Bearer ")) {
            authorization = authorization.replaceFirst("Bearer ", "");
        }
        return authorization;
    }
}
